package com.bkgy.modular.tpdidata_cal1630.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bkgy.controller.tPdiDataL3Tcm2280.entity.TPdiDataL3Tcm2280;
import com.bkgy.controller.tPdiDataL3Tcm2280.service.ITPdiDataL3Tcm2280Service;
import com.bkgy.controller.tpdol3data.entity.OutputSec;
import com.bkgy.modular.tpdidata_cal1630.entity.TPdiDataMes2280;
import com.bkgy.modular.tpdidata_cal1630.mapper.IPdiDataMesMapper;
import com.bkgy.modular.tpdidata_cal1630.service.ITPdiDataMesService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ITPdiDataMesServiceImpl extends ServiceImpl<IPdiDataMesMapper, TPdiDataMes2280> implements ITPdiDataMesService {
    private final ITPdiDataL3Tcm2280Service pdiTcm2280Service;

    @Override
    public OutputSec sumOutputSecInfo(Date beginDeate, long totalSec) {
        OutputSec sec = new OutputSec();

        LambdaQueryWrapper<TPdiDataMes2280> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(TPdiDataMes2280::getInnerInMatNo, TPdiDataMes2280::getOutputSe, TPdiDataMes2280::getToc);
        wrapper.ge(TPdiDataMes2280::getToc, beginDeate).orderByAsc(TPdiDataMes2280::getToc);
        List<TPdiDataMes2280> mesList = list(wrapper);
        int sumSec = 0, rollNum = 0;
        List<String> entIdList = new ArrayList<>();
        String firstEntId = null, lastEntId = null;
        for (int i = 0; i < mesList.size(); i++) {
            TPdiDataMes2280 me = mesList.get(i);
            if (i == 0) {
                firstEntId = me.getInnerInMatNo();
                lastEntId = me.getInnerInMatNo();
            }
            if (sumSec + me.getOutputSe() > totalSec) {
                break;
            }
            sumSec += me.getOutputSe();
            entIdList.add(me.getInnerInMatNo());
            lastEntId = me.getInnerInMatNo();
            rollNum++;
        }
        sec.setTotalSec(sumSec);
        sec.setTotalRoll(rollNum);
        sec.setFirstEntid(firstEntId);
        sec.setLastEntid(lastEntId);

        BigDecimal sumOutput = BigDecimal.ZERO;
        if (entIdList.size() > 0) {
            LambdaQueryWrapper<TPdiDataL3Tcm2280> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.select(TPdiDataL3Tcm2280::getEntid, TPdiDataL3Tcm2280::getInMatWt);
            wrapper2.in(TPdiDataL3Tcm2280::getEntid, entIdList);
            List<TPdiDataL3Tcm2280> pdiList = pdiTcm2280Service.list(wrapper2);
            for (TPdiDataL3Tcm2280 p : pdiList) {
                sumOutput = sumOutput.add(p.getInMatWt());
            }
        }
        sec.setTotalOutput(sumOutput);
        return sec;
    }
}
